#include "liboss/OssUploader.h"
#include "common/gclog.h"

using namespace liboss;

OssUploader::OssUploader() {

}

OssUploader::~OssUploader() {
    ShutdownSdk();
}

int OssUploader::InitUploader(const std::string &endPoint, const std::string &accessKeyId, const std::string &accessKeySecret) {
    if (endPoint.empty() || accessKeyId.empty() || accessKeySecret.empty()) {
        el("Init uploader failed");
        return -1;
    }
    m_endPoint = endPoint;
    m_accessKeyId = accessKeyId;
    m_accessKeySecret = accessKeySecret;
    InitializeSdk();
    m_clientConf = std::make_shared<ClientConfiguration>();
    m_client = std::make_shared<OssClient>(m_endPoint, m_accessKeyId, m_accessKeySecret, *m_clientConf);
    el("Init uploader success");
    return 0;
}

int OssUploader::UploadData(const std::string &bucketName, const std::string &objectName, const char *buffer) {
    if (m_client == nullptr) {
        el("Not init uploader");
        return -1;
    }
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>(buffer);
    auto outcome = m_client->PutObject(bucketName, objectName, content);
    if (!outcome.isSuccess()) {
        el("Upload data failed");
        return -1;
    }
    return 0;
}

int OssUploader::UploadFile(const std::string &bucketName, const std::string &objectName, const std::string &path) {
    if (m_client == nullptr) {
        el("Not init uploader");
        return -1;
    }
    auto outcome = m_client->PutObject(bucketName, objectName, path);
    if (!outcome.isSuccess()) {
        el("Upload data failed");
        return -1;
    }
    return 0;
}